package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"time"
	"xianzhi/service"
	"xianzhi/utils/wechat"
)

type BaseController struct {
	beego.Controller
}

func (c *BaseController) Prepare() {
	noLogin := map[string]string{
		"UserController/Register": "1",
		"UserController/DoRegister": "1",
		"UserController/Login": "1",
		"UserController/DoLogin": "1",
		"UserController/FindPassword": "1",
		"UserController/DoFindPassword": "1",
		"UserController/Logout": "1",
	}
	needWechatAuth := map[string]string{
		"UserController/Register": "1",
	}

	ctl, act := c.GetControllerAndAction()
	p := fmt.Sprintf("%s/%s", ctl, act)
	c.Data["curUrl"] = p

	if _, ok := needWechatAuth[p]; ok { // 需要网页授权
		code := c.GetString("code")
		if len(code) <= 0 {
			info := c.GetSession("wechatUserInfo")
			if info == nil {
				domain := c.Ctx.Input.Domain()
				tUrl := beego.URLFor(fmt.Sprintf("controllers.%s.%s", ctl, act))
				redirectUrl := fmt.Sprintf("http://%s%s", domain, tUrl)
				appId := beego.AppConfig.String("wechatappid")
				url := fmt.Sprintf("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo#wechat_redirect",
					appId, redirectUrl)
				c.Redirect(url, 302)
				return
			}
		} else {
			wechatUserInfo := wechat.GetWechatUserInfoByCode(code)
			info, _ := json.Marshal(wechatUserInfo)
			c.SetSession("wechatUserInfo", string(info))
		}
	}

	if _, ok := noLogin[p]; !ok {
		userId := c.GetSession("userId")
		if userId == nil {
			c.Redirect(beego.URLFor("controllers.UserController.Login"), 302)
			return
		}

		p := map[string]interface{}{}
		p["id"] = userId
		p["convert"] = true
		c.Data["loginUser"] = service.GetUserInfo(p)
		c.Data["currentTime"] = time.Now().Format("2006-01-02 15:04")

		p = map[string]interface{}{}
		p["id"] = 1
		c.Data["siteConfig"] =  service.GetSiteConfigInfo(p)

		p = map[string]interface{}{}
		p["userId"] = userId
		c.Data["orderCount"], _ = service.GetOrderList(p)
	}
}